﻿@page "/form"

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components.Forms

<div class="row">
    <div class="col-5">
        @if(message is not null)
        {
            if(message != "")
            {
                <div class="alert alert-danger">@message</div>
            }
            else
            {
                <div class="alert alert-success">表单提交成功</div>
            }
        }
        <EditForm Model="Model" OnSubmit="Submit" OnInvalidSubmit="InValidSubmit" OnValidSubmit="ValidSubmit">
            <DataAnnotationsValidator/>
            <div class="mt-2">
                <label class="col-2 form-label">用户名：</label>
                <InputText @bind-Value="Model.UserName" class="form-control col-10" />
                <ValidationMessage For="()=>Model.UserName" />
            </div>
            <div class="mt-2">
                <label class="col-2 form-label">密码：</label>
                <InputText type="password" @bind-Value="Model.Password" class="form-control col-10" />
                <ValidationMessage For="()=>Model.Password" />
            </div>
            <div class="mt-2">
                <button type="submit" class="btn btn-primary">
                    登录
                </button>
            </div>
        </EditForm>
    </div>
</div>

@code{
    class UserLoginViewModel
    {
        [Required(ErrorMessage ="用户名不能是空")]
        [StringLength(10,ErrorMessage ="不能大于10")]
        public string UserName { get; set; }
        [Required]
        public string Password { get; set; }
    }

    UserLoginViewModel Model = new();

    string? message;

    Task InValidSubmit(EditContext context)
    {
        message = "Invalid";
        return Task.CompletedTask;
    }

    Task ValidSubmit(EditContext context)
    {
        message = "Valid";
        return Task.CompletedTask;
    }

    Task Submit(EditContext context)
    {
        //var valid = context.Validate();
        //if (!valid)
        //{
        //    //表单验证失败
        //    message = "表单有问题";
        //    return Task.CompletedTask;
        //}
        //表单ok 可以提交

        //Service.Create(Model);
        message = "";
        return Task.CompletedTask;
    }
}